package com.ice.framework.views

import android.content.Context
import android.os.Build
import android.util.AttributeSet
import android.view.ViewTreeObserver
import android.widget.RelativeLayout
import androidx.annotation.RequiresApi
import kotlin.math.abs


class SquareRelativeLayout : RelativeLayout {
    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes)

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        //provide a square Preview in xml (not possible in certain cases)
        if (isInEditMode) { // if height < width : call super method with heightSpec for all sides
            if (abs(heightMeasureSpec) < abs(widthMeasureSpec)) {
                super.onMeasure(heightMeasureSpec, heightMeasureSpec)
            } else {
                super.onMeasure(widthMeasureSpec, widthMeasureSpec)
            }
        }
        init()
    }

    /**
     * Callback method to be invoked when the view tree is about to be drawn.
     * At this point, all views in the tree have been measured and given a frame.
     * So calculate the bounds before rendering the layout.
     */
    private fun init() {
        this.viewTreeObserver.addOnPreDrawListener(ViewTreeObserver.OnPreDrawListener {
            if (width != height) { //Get the smaller dimension of height and width
                val squareSize = width.coerceAtMost(height)
                //Set the dimensions to a Square
                val lp = layoutParams
                lp.width = squareSize
                lp.height = squareSize
                requestLayout()
                return@OnPreDrawListener false
            }
            true
        })
    }
}